# -*- coding: utf-8 -*-
from common.mymako import render_mako_context, render_json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from .models import Zhihu
import requests
import hashlib
from lxml import etree
from home_application.forms import FileUploadForm
from celery import task
import time
from common.log import logger
from home_application.models import MultRecord
import datetime
import json
from django.contrib import messages


def bkfour(request):

    return render_mako_context(request, '/home_application/bkfour.html')


###########################################################
def demo(request):
    '''
    @node: 请求数据接口
    '''
    all_record = MultRecord.objects.all()
    data = []
    [ data.append(i.to_json()) for i in all_record ]
    return HttpResponse(json.dumps(data))

def calc(request):
    '''
    @node: 该函数将只作为访问响应
    '''
    return render_mako_context(request, '/home_application/calc.html')

def multiplication_computer(request):
    """
    @node: 计算，入库
    """
    multiplier = int(request.POST.get('multiplier'))
    multiplicand = int(request.POST.get('multiplicand'))
    mult_result = multiplier * multiplicand
    mult_time =  time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    mult_user = request.user.username

    try:
        mult_record = MultRecord(multiplier=multiplier,multiplicand=multiplicand,mult_result=mult_result,mult_time=mult_time,mult_user=mult_user)
        mult_record.save()
    except Exception,e:
        print e
    return render_json({'result': True,'mult_result': mult_result})


def create(request):
    '''
    @node: 表格新增操作
    @summary: 注意这里是添加，即想数据库插入数据，id是自增的.
    '''
    models = request.POST.get('models', '{}')
    models_json = json.loads(models)

    create_data_list = []
    try:
        for data in models_json:
            multiplier = data['multiplier']
            multiplicand = data['multiplicand']
            mult_result = data['mult_result']
            mult_time = datetime.datetime.strptime(data['mult_time'], '%Y-%m-%d %H:%M:%S')
            mult_user = data['mult_user']
            mult = MultRecord.objects.create(
                multiplier=multiplier,
                multiplicand=multiplicand,
                mult_result=mult_result,
                mult_time=mult_time,
                mult_user=mult_user)
            data['id'] = mult.id
            create_data_list.append(data)

        result = {'result': True, 'data': create_data_list}
        print create_data_list
    except Exception, e:
        print e
        print 'add failed.......'
        logger.error(u"添加新纪录失败，%s" % e)
        result = {'result': False, 'message': u"添加新纪录失败，%s" % e}
    return render_json(result)

def update(request):
    '''
    @node: 表格更新操作
    '''
    models=request.POST.get('models','{}')
    models_json = json.loads(models)
    update_data_list=[]
    try:
        for data in models_json:
            mult_id = data['id']
            multiplier = data['multiplier']
            multiplicand = data['multiplicand']
            mult_result = data['mult_result']
            mult_time = datetime.datetime.strptime(data['mult_time'],'%Y-%m-%d %H:%M:%S')
            mult_user = data['mult_user']
            MultRecord.objects.filter(id=mult_id).update(
                multiplier = multiplier,
                multiplicand = multiplicand,
                mult_result = mult_result,
                mult_time = mult_time,
                mult_user = mult_user)

            update_data_list.append(data)


        result = {'result': True, 'data': update_data_list}
        logger.info(u"更新纪录成功")
    except Exception, e:
        logger.error(u"更新纪录失败，%s" % e)
        result = {'result': False, 'message': u"更新纪录失败，%s" % e}
    return render_json(result)

def destroy(request):
    '''
    @node: 表格删除操作
    '''
    models = request.POST.get('models', '{}')
    models_json = json.loads(models)
    delete_data_list = []
    print models
    try:
        for data in models_json:
            mult_id = data['id']
            MultRecord.objects.filter(id=mult_id).delete()
            delete_data_list.append(data)
        print delete_data_list
        result = {'result': True, 'data': delete_data_list}
        print u'删除成功'
    except Exception, e:
        logger.error(u"更新纪录失败，%s" % e)
        result = {'result': False, 'message': u"删除纪录失败，%s" % e}
    return render_json(result)

# def popup_edit(request):
#     """
#     @note: 弹出层编辑
#     @param operation:操作。value为create、update、destroy
#     """
#     operation = request.POST.get('operation')
#     if operation == 'create':
#         return create(request)
#     if operation == 'update':
#         return update(request)
#     if operation == 'destroy':
#         return destroy(request)


###########################################################

def bkfour_res(request):
    string = "congratulation!"
    return HttpResponse(string)


def outmanapp_index(request):
    return render_mako_context(request,'/home_application/outmanapp.html')



def outmanapp_zhihu(request):
    if request.method == 'POST':
        Zhihu.objects.all().delete()
        zhihu_hot = {}
        head = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36'}
        def get_html_source(url):
            html = requests.get(url,headers=head)
            html.encoding = 'utf-8'
            selector = etree.HTML(html.text)

            contener = selector.xpath('//*[@class="feed-item feed-item-hook  folding"]')

            for each in contener:
                hot_title = each.xpath('.//*[@class="feed-content"]/h2/a/text()')[0].strip('\n')
                hot_url = 'https://www.zhihu.com'+ each.xpath('.//*[@class="feed-content"]/h2/a/@href')[0]

                try:
                    zhihu_hot[hot_title]=hot_url
                    Zhihu.objects.create(title=hot_title,links=hot_url)
                    Zhihu.objects.save()
                except:
                    pass

        url = 'https://www.zhihu.com/topic/19607535/hot'
        get_html_source(url=url)

        return render_mako_context(request,'/home_application/outmanapp.html',{'data':zhihu_hot.items()})
    return render_mako_context(request,'/home_application/outmanapp.html')



def upload(request):
    information ={}

    if request.method == 'POST':

        my_form = FileUploadForm(request.POST, request.FILES)
        if my_form.is_valid():
            uppath = '/data/uploads/'
            f = my_form.cleaned_data['my_file']
            handle_uploaded_file(f,updir=uppath)
            information["FileName: "] = f.name
            information["FileSize: "] = str(int(f.size) / 1024)+'K'
            #@print int(f.size) / 1024
            information["FileMD5: "] = CalcMD5(uppath + f.name)
            information["FileLocation:"] = uppath + f.name
        my_form = FileUploadForm()
        #print information

        return render_mako_context(request, '/home_application/upload.html',{'form': my_form,"information":information})
    else:
        my_form = FileUploadForm()
        return render_mako_context(request, '/home_application/upload.html', {'form': my_form,"information":information})


def handle_uploaded_file(f,updir):
    with open(updir+f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

def CalcMD5(filepath):
    with open(filepath,'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        print(hash)
        return hash



@csrf_exempt
def endecrypt(request):
    from .crypto import prpcrypt
    information = {}
    result = False
    if request.method == 'POST':
        result = True
        # 获取各个输入值!
        res = request.POST.get('blueking', None)
        key = request.POST.get('key', None)
        encontent =  request.POST.get('encontent',None)
        decontent =  request.POST.get('decontent',None)

        ende = prpcrypt(key)


        if res == 'en':

            enres = ende.encrypt(encontent)
            information["key:"] = key
            information[u"加密结果: "] = enres
            information[u"加密内容: "] = encontent
            return render_mako_context(request, '/home_application/crypto.html',
                                       {'string': information, 'result': result, 'action': 'en'})
        elif res == 'de':
            deres = ende.decrypt(decontent)
            information["key:"] = key
            information[u"解密结果: "] = deres
            information[u"解密内容: "] = decontent
            return render_mako_context(request, '/home_application/crypto.html',
                                       {'string': information, 'result': result, 'action': 'de'})
    else:
        return render_mako_context(request, '/home_application/crypto.html', {'result': result})




def home(request):
    """
    首页
    """
    return render_mako_context(request, '/home_application/home.html')


def dev_guide(request):
    """
    开发指引
    """
    return render_mako_context(request, '/home_application/dev_guide.html')


def contactus(request):
    """
    联系我们
    """
    return render_mako_context(request, '/home_application/contact.html')

##########################################################################################################
# 普通任务
@csrf_exempt
def execute_task(request):
    """
    @summary: 请求函数入口
    """
    res = False
    if request.method == 'POST':
        res = True
        param1 = request.POST.get('param1')
        param2 = request.POST.get('param2')
        custom_task.apply_async(args=[param1, param2])
        string = u'你提交的任务正在后台执行......'
        return render_mako_context(request, '/home_application/excue_task.html',{'string': string, 'res':res})
    string = ''
    return render_mako_context(request, '/home_application/excue_task.html',{'string': string, 'res':res})

@task()
def custom_task(param1, param2):
    """
    @summary: 自定义逻辑
    """
    # 定义自己的任务逻辑(比如大数据的计算等...)
    startime = time.time()             # 记录该逻辑代码起始时间
    logger.info(u"普通开始执行...{}".format(startime))
    time.sleep(10)
    res = int(param1) + int(param2)
    endtime = time.time()               # 记录该逻辑代码结束时间
    logger.info(u"普通结束执行...{}".format(endtime))

    usetime = endtime - startime       # 计算该逻辑代码执行耗时

    logger.info(u"普通任务执行完毕，耗时：{}".format(usetime)) # 在 celery 执行过程中记录该消息!
    return res




# 
def esb_t(request):
    return render_mako_context(request,"/home_application/home_tmpl.html")

from blueking.component.shortcuts import get_client_by_request
from django.conf import settings
# import settings
def test(request):
    client = get_client_by_request
    kwargs = {
        "app_code": settings.APP_ID,
        "ap_secret": settings.APP_TOKEN,
        "bk_token": request.COOKIES['bk_token'], # 获取请求时的bk_token(浏览器中可见)
        "app_id": "4"
    }

    result = client.job.get_task(kwargs)
    if not result['result']:
        return render_json({'result': True, 'message': result['message'] or u'执行失败'})
    task_id = None
    for info in result['data']:
        if info['name'] == 'test':
            task_id = info['id']

    kwargs['task_id'] = task_id

    result = client.job.execute_task(kwargs)
    message = result.get('message')
    if result['result']:
        return render_json({'result': True, 'message': message or u'执行成功'})
    return render_json({'result': True, 'message': message or u'执行失败'})

